package com.duke.payphone.buy;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;
import com.duke.payphone.scan.IntentIntegrator;
import com.duke.payphone.scan.IntentResult;


/**
 * activity is called by the ROOT
 * 
 * this activity is never seen, its calls the qr scanner using intent
 * and returns the TID from the qr scanner, then it sends info to the server *
 * 
 * if TID doesnt exist (server returns invalid) or qr scan failed, toast =
 * "Scan failed", go back to root
 * 
 * if server returns valid (server also returns transaction details), write
 * transaction info
 * to the globalvars (to display in the next activity), and proceed to BuyInfo,
 * and finish() this
 * 
 * @author Michael
 * 
 */
public class BuyNewActivity extends Activity {

    private Global globalvars;
    private String scanResultStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_new);

        globalvars = (Global) getApplicationContext();
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_buy_new, menu);
        // return true;
        return false;
    }

    /**
     * executing a scan
     * 
     * @param v
     */
    public void executeScan (View v) {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.initiateScan();
    }

    /**
     * returning from a scan
     */
    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent intent) {
        IntentResult scanResult =
                IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanResult != null) {
            scanResultStr = scanResult.getContents();
            scanHandler();
        }
    }

    /**
     * handling the scan result
     */
    private void scanHandler () {

        if (true) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onBuyNewValid(response);
                    }
                    else {
                        onBuyNewInvalid(response);
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {

        Toast.makeText(globalvars, "QR contents: " + scanResultStr, Toast.LENGTH_SHORT).show();

        // prepare the map
        Map<String, Serializable> request = MapFactory.createTransmitMap("buynew");
        request.put("decodedid", scanResultStr);

        return request;
    }

    /**
     * @param response
     */
    private void onBuyNewValid (Map<String, Serializable> response) {

        Toast.makeText(globalvars, "Retrieving transation info...", Toast.LENGTH_SHORT).show();

        Intent toBuyInfo = new Intent(this, BuyInfoActivity.class);

        if (response.containsKey("productname")) {
            toBuyInfo.putExtra("productname", (String) response.get("productname"));
        }
        if (response.containsKey("price")) {
            toBuyInfo.putExtra("price", (String) response.get("price"));
        }
        if (response.containsKey("date")) {
            toBuyInfo.putExtra("date", (String) response.get("date"));
        }

        if (response.containsKey("seller")) {
            toBuyInfo.putExtra("seller", (String) response.get("seller"));
        }

        startActivity(toBuyInfo);
        finish();
    }

    /**
     * @param response
     */
    private void onBuyNewInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Unable to retrieve transaction. Please try again.",
                       Toast.LENGTH_SHORT).show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        // request
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
